package com.zm.spring.jdbc;

import com.zm.spring.jdbc.Bean.Account;
import com.zm.spring.jdbc.dao.OpRecordDao;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/bank/*")
public class BankServlet extends BasicServlet{

    protected void withdraw(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        ApplicationContext cxt = (ApplicationContext) servletContext.getAttribute("cxt");
        BankBiz dao = cxt.getBean(BankBiz.class);
        Account userInfo = (Account) req.getSession().getAttribute("userInfo");
        System.out.println("userInfo = " + userInfo);
        int aid = userInfo.getId();
        Double money =Double.parseDouble(req.getParameter("money"));
        System.out.println("aid = " + aid);
        int result = 0;
        try {
            dao.withdraw(aid,money);
            result = 1;
        } catch (BizException e) {
            result = -1;
        }
        this.send(resp,result);
    }

    protected void deposit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        ApplicationContext cxt = (ApplicationContext) servletContext.getAttribute("cxt");
        BankBiz dao = cxt.getBean(BankBiz.class);
        Account userInfo = (Account) req.getSession().getAttribute("userInfo");
        System.out.println("userInfo = " + userInfo);
        int aid = userInfo.getId();
        Double money =Double.parseDouble(req.getParameter("money"));
        System.out.println("aid = " + aid);
        dao.deposit(aid,money);
        this.send(resp,1);
    }

    protected void transfer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext servletContext = this.getServletContext();
        ApplicationContext cxt = (ApplicationContext) servletContext.getAttribute("cxt");
        BankBiz dao = cxt.getBean(BankBiz.class);
        Account userInfo = (Account) req.getSession().getAttribute("userInfo");
        System.out.println("userInfo = " + userInfo);
        int aid1 = userInfo.getId();
        Double money =Double.parseDouble(req.getParameter("money"));
        int aid2 =Integer.parseInt(req.getParameter("aid"));
        System.out.println("aid1 = " + aid1);
        System.out.println("aid2 = " + aid2);
        int result = 0;
        try {
            dao.transfer(aid1,aid2,money);
            result = 1;
        } catch (BizException e) {
            result = -1;
        }
        this.send(resp,result);
    }
}
